__author__ = 'xiaosu'

import run_a_command
import sys
sys.path.append('..')


from config import SQLALCHEMY_DATABASE_URI
from sqlalchemy import create_engine
from sqlalchemy.orm import backref, mapper, relation, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,String,Integer,Boolean,Text,ForeignKey,UniqueConstraint
import argparse

import os
os.chdir("..")


Base = declarative_base()
engine = create_engine(SQLALCHEMY_DATABASE_URI,echo=False)
DB_Session = sessionmaker(bind=engine)
session = DB_Session()

# print session.execute('select * from clusters ').fetchall()

class Clusters(Base):
    __tablename__ = "clusters"
    clusterid = Column(Integer, primary_key = True)
    clustername = Column(String(64), unique = True)
    runuser = Column(String(64))
    audit = Column(Boolean, default = True)
    enabled = Column(Boolean, default = True)
    comment = Column(Text)
    hosts =  relation('Hosts', backref = 'clusters', lazy = 'dynamic')

    def __init__(self,clustername,runuser,audit=True,enabled=True,comment="no comment now"):
        self.clustername = clustername
        self.runuser = runuser
        self.audit = audit
        self.enabled = enabled
        self.comment = comment

class Hosts(Base):
    __tablename__ = 'hosts'
    hostid = Column(Integer , primary_key = True)
    host_ip = Column(String(15))
    login_name = Column(String(64))
    login_passwd = Column(String(64))
    root_passwd = Column(String(64))
    server_port = Column(Integer, default = 22)
    clusterid = Column(Integer, ForeignKey('clusters.clusterid'))
    audit = Column(Boolean, default = True)
    enabled = Column(Boolean, default = True)
    comment = Column(Text)
    __table_args__=(UniqueConstraint('host_ip','login_name'),)


    def __init__(self,ipaddress,username,password,rootpasswd,serverport,clusterid,audit=True,enabled=True,comment="no comment now"):
        self.host_ip = ipaddress
        self.login_name = username
        self.login_passwd = password
        self.root_passwd = rootpasswd
        self.server_port = serverport
        self.audit = audit
        self.enabled = enabled
        self.comment = comment
        self.clusterid = clusterid



def list_clusters():
    query= session.query(Clusters)
    print "id  name  enabled"
    for i in query:
        print str(i.clusterid)+"  "+i.clustername+ "  "+ str(i.enabled)

def list_hosts(id):
    if id=="all":
        query=session.query(Hosts)
        print "hostid  host_ip  username  password rootpasswd"
        for i in query:
            print str(i.hostid)+"  "+i.host_ip+"  "+i.login_name+"  "+i.login_passwd+"  "+i.root_passwd
    else :
        query=session.query(Hosts).filter_by(clusterid=id)
        for i in query:
            print str(i.hostid)+"  "+i.host_ip+"  "+i.login_name+"  "+i.login_passwd+"  "+i.root_passwd

#query=session.query(Clusters)

# print query
# print list(query)
# for i in query:
#     print i.clustername

#query=session.query(Hosts)

# print query
# print list(query)
# for i in query:
#     print i.host_ip
#     print i.login_passwd


parser = argparse.ArgumentParser(description='This is a command line tools for octopus')

group=parser.add_mutually_exclusive_group()

group.add_argument('--list_clusters',help='list all clusters',action="store_true")
group.add_argument('--list_hosts',help='list hosts in clusterid ,"all" for all',metavar='clusterid' )
group.add_argument('--run_command_cluster',help='run command in specific cluster, specified by clusterid',metavar='command')
group.add_argument('--run_command_host',help='run command on specific host,specified by hostid',metavar="command")
parser.add_argument('--hostid',help='hostid required by --run_command_host')
parser.add_argument('--clusterid',help='clusterid required by --run_command_cluster')
args=parser.parse_args()
#print args.command
if  args.list_clusters:
    list_clusters()
elif args.list_hosts:
    list_hosts(args.list_hosts)
elif args.run_command_host:
    command=args.run_command_host
    hostid=args.hostid
    if hostid == None:
        print "please specific the hostid"
        exit(1)
    else:
        host=session.query(Hosts).filter_by(hostid=hostid).first()
        # print host.enabled
        run_command_host=run_a_command.host_command(host.host_ip,host.login_name,host.login_passwd,command,host.audit,host.enabled,host.server_port,host.root_passwd,False)
        result=run_command_host.run()
        print host.host_ip
        print "======> The command is :"
        print command
        print "======> The result is :"
        print result
elif args.run_command_cluster:
    command=args.run_command_cluster
    clusterid=args.clusterid
    if clusterid == None:
        print "please specific the clusterid"
        exit(1)
    else:
        query=session.query(Hosts).filter_by(clusterid=clusterid)
        host_list=[]
        for i in query:
            host_list.append([i.host_ip,i.login_name,i.login_passwd,command,i.audit,i.enabled,i.server_port,i.root_passwd,False])
        run_command_cluster=run_a_command.multi_run(host_list)
        result=run_command_cluster.para_run()
        for i in result:
            print i[0]
            print i[1]